<style>
    body {
        padding: 15px 10px
    }
    body .layui-form fieldset.layui-elem-field {
        margin: 0 0 10px 0
    }
</style>
<script>
    // 表单
    layui.use(['element', 'form', 'upload', 'layedit', 'laydate', 'colorpicker', 'layer', 'util'], function () {
        var form = layui.form,
            upload = layui.upload,
            layedit = layui.layedit,
            laydate = layui.laydate,
            colorpicker = layui.colorpicker,
            layer = layui.layer,
            util = layui.util,
            $ = layui.jquery;

        var site_url = '{$site_url}';

        // 获取应用、控制器和方法
        var module = '{$module}'.toLowerCase(),
            controller = '{$controller}'.toLowerCase(),
            action = '{$action}'.toLowerCase();

        // 如果非框架内
        if (self.frameElement && self.frameElement.tagName == 'IFRAME' && action !== 'index') {
            if (parent.layer.getFrameIndex(window.name))
                $('form.layui-form .layui-elem-field').remove();
            else
                !$('form.layui-form .layui-elem-field').length && $('form.layui-form').prepend('<fieldset class="layui-elem-field layui-field-title"><legend>' + (action == 'create' ? '添加' : (action == 'edit' ? '编辑' : '信息')) + '</legend></fieldset>');
        }

        // 日期
        $('form .date').each(function () {
            laydate.render({
                elem: $(this).attr('id') ? '#' + $(this).attr('id') : 'input[name="' + $(this).attr('name') + '"]',
                type: $(this).data('type') || 'date'
            });
        });

        // 颜色
        $('form .color').each(function () {
            var input_id = $(this).attr('id') || $(this).attr('name');
            $(this).parent().parent().append('<div class="layui-inline" style="left: -11px;"><div id="' + input_id + '-render"></div></div>');
            colorpicker.render({
                elem: '#' + input_id + '-render',
                done: function (color) {
                    $('input[name="' + input_id + '"]').val(color);
                }
            });
        });

        // 上传
        $('form .upload').each(function () {
            var input_id = $(this).attr('id') || $(this).attr('name');
            $(this).parent().append('<div class="layui-upload-list" style="position:relative;"></div>');
            $(this).parent().parent().append('<button type="button" class="layui-btn layui-btn-primary" id="' + input_id + '-render"><i class="layui-icon layui-icon-upload"></i> 上传</button>');
            if (/\.(gif|jpg|jpeg|png|bmp|webp|psd|svg|tiff)$/gi.test($(this).val())) {
                $(this).parent().find('.layui-upload-list').html('<i class="layui-icon layui-icon-close-fill" style="position:absolute;bottom:-10px;left:-10px;opacity:0.8;cursor:pointer;"></i><img src="' + $(this).val() + '" alt="Preview" style="max-width:92px" onerror="this.parentNode.innerHTML=\'404 Error\'" />');
            }
            upload.render({
                elem: '#' + input_id + '-render',
                url: site_url + '/' + module + '/media/upload.html',
                data: {},
                before: function () {
                    layer.load();
                },
                done: function (res, index, upload) {
                    layer.closeAll('loading');
                    if (res.code > 0) return layer.msg(res.msg, { icon: 2 });
                    //上传成功
                    $(this.item).prev().find('input[name="' + input_id + '"], input[id="' + input_id + '"]').val(res.data.src)
                    if (/\.(gif|jpg|jpeg|png|bmp|webp|psd|svg|tiff)$/gi.test(res.data.src)) {
                        $(this.item).prev().find('.layui-upload-list').html('<i class="layui-icon layui-icon-close-fill" style="position:absolute;bottom:-10px;left:-10px;opacity:0.8;cursor:pointer;"></i><img src="' + res.data.src + '" alt="Preview" style="max-width:92px" onerror="this.parentNode.innerHTML=\'404 Error\'" />');
                    }
                },
                error: function (index, upload) {
                    layer.closeAll('loading');
                }
            });
        });
        $('form .upload').change(function () {
            if (/\.(gif|jpg|jpeg|png|bmp|webp|psd|svg|tiff)$/gi.test($(this).val())) {
                $(this).parent().find('.layui-upload-list').html('<i class="layui-icon layui-icon-close-fill" style="position:absolute;bottom:-10px;left:-10px;opacity:0.8;cursor:pointer;"></i><img src="' + $(this).val() + '" alt="Preview" style="max-width:92px" onerror="this.parentNode.innerHTML=\'404 Error\'" />');
            } else {
                $(this).parent().find('.layui-upload-list').html(null);
            }
        });
        $('form .layui-upload-list').on('click', '.layui-icon-close-fill', function () {
            $(this).parent().prev().val(null);
            $(this).parent().html(null);
        });

        // layedit富文本
        var editors = [];
        layedit.set({
            uploadImage: {
                url: site_url + '/' + module + '/media/upload.html', //接口url
                type: 'post', //默认post
            }
        });
        $('form .editor').each(function () {
            var editor_id = $(this).attr('id') || $(this).attr('name');
            $(this).attr('id', editor_id);
            $(this).attr('lay-verify', editor_id);
            editors[editor_id] = layedit.build(editor_id, {
                tool: [
                    'strong', //加粗
                    'italic', //斜体
                    'underline', //下划线
                    'del', //删除线
                    '|', //分割线
                    'left', //左对齐
                    'center', //居中对齐
                    'right', //右对齐
                    '|', //分割线
                    'link', //超链接
                    'unlink', //清除链接
                    'face', //表情
                    'image', //插入图片
                ]
            });
        });

        // 监听提交
        form.on('submit(submit)', function (data) {
            if ('undefined' !== typeof KindEditor && window.editor1) {
                data.field.content = window.editor1.html();
            }
            for (var editor in editors) {
                data.field[editor] = layedit.getContent(editors[editor]);
            }
            $.post(site_url + '/' + module + '/' + controller + '/' + (action == 'edit' ? 'update' : 'save' + (action == 'create' ? '' : '_' + action)) + '.html', data.field, function (res) {
                if (res.code) return layer.alert(res.msg, { icon: 2 });
                layer.alert(res.msg, { icon: 1 });
                setTimeout(function () {
                    var _ta = window, parentIndex = parent.layer.getFrameIndex(window.name);
                    if (typeof parentIndex !== 'undefined') {
                        parent.layer.close(parentIndex);
                        _ta = parent.window;
                    }
                    if (typeof _ta.layui.table !== 'undefined' && _ta.layui.table.index == 1 && _ta.render && _ta.render.elem) {
                        _ta.layui.table.reload(_ta.render.elem.replace(/#/, ''));
                    } else if (typeof res.url !== 'undefined' && res.url) {
                        _ta.location.href = res.url;
                    } else {
                        _ta.location.reload();
                    }
                }, 1000);
            }, 'json');
            return false;
        });

        // 别名翻译
        $('form .translate-slug').click(function () {
            var _this = $(this);
            var title = $('form input[name="title"], form input[name="name"]');
            var slugField = $('form input[name="slug"]');
            if (title.val().trim() == '') return layer.msg('标题或名称不能为空', { icon: 2 });
            if ('Pinyin' in window && window.Pinyin.isSupported() && 'navigator' in window && !window.navigator.onLine) {
                // 离线转拼音
                var pinyin = '';
                var tokens = Pinyin.parse(title.val().trim());
                var lastToken;
                tokens.forEach(function (v, i) {
                    if (v.type === 2) {
                        var formatTarget = v.target ? v.target.toLowerCase() : '';
                        pinyin += pinyin && !/\n|\s/.test(lastToken.target) ? ' ' + formatTarget : formatTarget;
                    } else {
                        pinyin += (lastToken && lastToken.type === 2 ? ' ' : '') + v.target;
                    }
                    lastToken = v;
                });
                slugField.val(pinyin);
            } else {
                // 否则使用接口（需联网）转英语
                icon = new Image();
                icon.src = 'https://www.google.com/favicon.ico?t=' + new Date().getTime();
                _this.addClass('layui-btn-disabled').attr('disabled', true).parent().find('.loading').removeClass('layui-hide');
                var timer = setTimeout(function () {
                    icon.onerror = icon.onload = null;
                    baidu_translate();
                }, 3000);
                icon.onerror = function () {
                    clearTimeout(timer);
                    timer = null;
                    baidu_translate();
                }
                icon.onload = function () {
                    clearTimeout(timer);
                    timer = null;
                    google_translate();
                }
                // 谷歌翻译
                function google_translate() {
                    $.ajax({
                        url: 'https://translate.googleapis.com/translate_a/single',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            client: 'webapp',
                            dt: 't',
                            dj: 1,
                            ie: 'UTF-8',
                            oe: 'UTF-8',
                            sl: 'zh-CN',
                            tl: 'en',
                            tk: getTk(title.val().trim()),
                            q: title.val().trim()
                        },
                        success: function (res) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            if (res && res.sentences) {
                                slugField.val($.map(res.sentences, function (el) {
                                    return el.trans.replace(/[\W]/g, ' ');
                                }).join(' ').replace(/\s+/g, ' ').trim());
                            }
                        },
                        error: function (XMLHttpRequest, textStatus) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                        },
                    });
                }
                // 百度翻译
                function baidu_translate() {
                    $.ajax({
                        url: site_url + '/api/baidu_translate',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            query: title.val().trim(),
                            from: 'zh',
                            to: 'en',
                            transtype: 'translang',
                            simple_means_flag: 3,
                            sign: getTk(title.val().trim(), 1),
                            token: '853eba4bc7ac9601ef8fff761c7cf8cf',
                        },
                        success: function (res) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            if (res && res.trans_result && res.trans_result.data) {
                                slugField.val($.map(res.trans_result.data, function (el) {
                                    return el.dst.replace(/[\W]/g, ' ');
                                }).join(' ').replace(/\s+/g, ' ').trim());
                            }
                        },
                        error: function (XMLHttpRequest, textStatus) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                        },
                    });
                }
                // 谷歌代理
                function proxy_translate() {
                    $.ajax({
                        url: 'https://api.translate.zvo.cn/translate.json',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            from: 'chinese_simplified',
                            to: 'english',
                            text: JSON.stringify([title.val().trim()])
                        },
                        beforeSend: function () {
                            _this.addClass('layui-btn-disabled').attr('disabled', true).parent().find('.loading').removeClass('layui-hide');
                        },
                        success: function (res) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            if (res && res.result) {
                                slugField.val(res.text.join(' ').replace(/[\W]/g, ' ').replace(/\s+/g, ' ').trim());
                            }
                        },
                        error: function (XMLHttpRequest, textStatus) {
                            _this.removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                            layer.msg(textStatus + ': ' + XMLHttpRequest.status, { icon: 2 });
                        },
                    });
                }
            }
        });

        // 字数统计
        var characters_count = function () {
            if ($('form .characters-count').length) {
                $('form .characters-count').each(function (i, elem) {
                    if ($(elem).prev().val().trim().length) {
                        var str = $(elem).prev().val().trim();
                        var len = str.length;
                        for (var j in str) {
                            if (str[j].charCodeAt(0).toString(16).length == 4) len += 1;
                        }
                        $(elem).html('<span style="color:#f00;font-weight:bold">' + len + '</span> ( ≤ ' + (i == 0 ? '60' : '140') + ' characters)');
                    } else {
                        $(elem).html('');
                    }
                });
            }
        }
        characters_count();
        $('form input[name="seo_title"], form textarea[name="seo_description"]').on('keyup change', characters_count);

        // Baidu 关键词建议
        window.bdsug = {
            sug: function (data) {
                $('form .keywords-suggest').removeClass('layui-btn-disabled').attr('disabled', false).parent().find('.loading').addClass('layui-hide');
                if (data && data.s.length) {
                    var arr = [];
                    for (var i = 0; i < data.s.length; i++) {
                        arr.push('<button type="button" class="layui-btn layui-btn-primary layui-btn-sm suggest-item">' + data.s[i] + '</button>');
                    }
                    $('form .keywords-suggest').parent().parent().find('.suggest-result').addClass('layui-input-block').html('<fieldset class="layui-elem-field"><div class="layui-field-box">' + arr.join('\n') + '</div></fieldset>');
                } else {
                    $('form .keywords-suggest').parent().parent().find('.suggest-result').removeClass('layui-input-block').html('');
                }
            }
        }

        // 关键词建议
        $('form .keywords-suggest').click(function () {
            var word = $('form input[name="title"], form input[name="name"], form input[name="webName"]').val().trim();
            if (word == '') return layer.msg('标题或名称不能为空', { icon: 2 });
            $(this).parent().parent().find('.suggest-result').removeClass('layui-input-block').html('')
            $(this).addClass('layui-btn-disabled').attr('disabled', true).parent().find('.loading').removeClass('layui-hide');
            // 百度关键词
            $.ajax({
                url: 'https://suggestion.baidu.com/su',
                type: 'get',
                dataType: 'jsonp',
                timeout: 5000,
                data: {
                    wd: word,
                    ie: 'UTF-8',
                    cb: 'window.bdsug.sug'
                }
            });
        });

        // 关键词建议结果
        $('form .suggest-result').on('click', '.suggest-item', function () {
            var title = $('form input[name="seo_title"]');
            var discription = $('form textarea[name="seo_description"]');
            if (title.val().trim()) {
                title.val(title.val().trim() + '-');
            }
            title.val(title.val().trim() + $(this).text());
            if (discription.val().trim()) {
                discription.val(discription.val().trim() + '，');
            }
            discription.val(discription.val().trim() + $(this).text());
            $(this).addClass('layui-btn-disabled').attr('disabled', true);
            characters_count();
        });

        // 谷歌百度翻译tk算法
        function getTk(a, t) {
            var gtk = t ? '320305.131321201' : '406398.2087938574';
            var e = gtk.split('.'), h = Number(e[0]) || 0, g = [], d = 0, i, j;
            for (var f = 0; f < a.length; f++) {
                var c = a.charCodeAt(f);
                128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ? (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240, g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
            }
            a = h;
            for (var d = 0; d < g.length; d++) {
                a += g[d];
                i = '+-a^+6';
                for (var k = 0; k < i.length - 2; k += 3) {
                    j = i.charAt(k + 2);
                    j = 'a' <= j ? j.charCodeAt(0) - 87 : Number(j);
                    j = '+' == i.charAt(k + 1) ? a >>> j : a << j;
                    a = '+' == i.charAt(k) ? a + j & 4294967295 : a ^ j;
                }
            }
            i = '+-3^+b+-f';
            for (var k = 0; k < i.length - 2; k += 3) {
                j = i.charAt(k + 2);
                j = 'a' <= j ? j.charCodeAt(0) - 87 : Number(j);
                j = '+' == i.charAt(k + 1) ? a >>> j : a << j;
                a = '+' == i.charAt(k) ? a + j & 4294967295 : a ^ j;
            }
            a ^= Number(e[1]) || 0;
            0 > a && (a = (a & 2147483647) + 2147483648);
            a %= 1E6;
            return a.toString() + '.' + (a ^ h);
        }
    });
</script>